package com.qianxunclub.mysql.base.dao;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.qianxunclub.mysql.base.model.BaseParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author chihiro.zhang
 */
@Slf4j
public class BaseDao<TMapper extends BaseMapper<TEntity>,TEntity,TParam extends BaseParam> extends ServiceImpl<TMapper,TEntity> {

    /**
     * 条件查询
     * @param ew
     * @return
     */
    public Page<TEntity> list(EntityWrapper<TEntity> ew,TParam baseParam){
        return this.getData(ew,baseParam);
    }

    /**
     * 条件查询
     * @param ew
     * @return
     */
    public Page<TEntity> list(EntityWrapper<TEntity> ew){
        return this.getData(ew,null);
    }

    private Page<TEntity> getData(EntityWrapper<TEntity> ew,TParam baseParam){
        Page<TEntity> page= new Page<>();
        boolean isPagination = false;
        if(baseParam != null){
            if(null != baseParam.getCurrent() ){
                page=new Page<>(baseParam.getCurrent(),baseParam.getSize());
                isPagination = true;
            }
            if(!StringUtils.isEmpty(baseParam.getOrderByField())){
                ew.orderBy(baseParam.getOrderByField(),baseParam.isAsc());
            }
            if(!StringUtils.isEmpty(baseParam.getDeleted())){
                ew.eq("deleted",baseParam.getDeleted());
            }
            if(!StringUtils.isEmpty(baseParam.getEnabled())){
                ew.eq("enabled",baseParam.getEnabled());
            }
        }
        if(isPagination){
            page = this.selectPage(page,ew);
        } else {
            List<TEntity> list = this.selectList(ew);
            page.setRecords(list);
            page.setTotal(list.size());
            page.setSize(list.size());
        }
        return page;
    }

}
